function buttonInit() {
    let btn = document.querySelector('.nav button');
    btn.onclick = function () {
        localStorage.removeItem('id');
        localStorage.removeItem('token');
        location.assign('/login.html');
    }
}
buttonInit();

// 左侧导航栏的js
function initSwithTab() {
    let tabSession = document.querySelector('.tab .tab-session');
    let tabFriend = document.querySelector('.tab .tab-friend');
    let lists = document.querySelectorAll('.list');

    tabSession.onclick = function () {
        tabSession.style.backgroundImage = 'url(image/对话.png)';
        tabFriend.style.backgroundImage = 'url(image/用户2.png)';
        lists[0].classList = 'list';
        lists[1].classList = 'list hide';
    }
    tabFriend.onclick = function () {
        tabSession.style.backgroundImage = 'url(image/对话2.png)';
        tabFriend.style.backgroundImage = 'url(image/用户.png)'
        lists[0].classList = 'list hide';
        lists[1].classList = 'list';
    }
}
initSwithTab();

function getUserInfo() {
    $.ajax({
        type: 'get',
        url: '/user/getUserInfo?userId=' + localStorage.getItem('id'),
        success: function (result) {
            if (result != null && result.data != null && result.data.userId != 0) {
                $('.user').text(result.data.userName);
            } else {
                alert("当前用户未登录!");
                location.assign('login.html');
            }
        }
    });
}
getUserInfo();

// 获取好友列表
function getFriendList() {
    $.ajax({
        type: 'get',
        url: '/user/getFriendList?userId=' + localStorage.getItem('id'),
        success: function (result) {
            let friendListUL = document.querySelector('#friend-list');
            friendListUL.innerHTML = '';
            console.log(result);
            console.log('result.data为：  ------', result.data);
            for (let friend of result.data) {
                let li = document.createElement('li');
                li.innerHTML = '<h4>' + friend.friendName + '</h4>';
                li.setAttribute('friend-id', friend.friendId);
                friendListUL.appendChild(li);

                // 给每个li添加点击事件
                li.onclick = function () {
                    clickFriend(friend);
                }
            }
        },
        error: function () {
            console.log('获取好友列表失败!');
        }
    });
}
getFriendList();

// TODO
function clickFriend(friend) {
    let sessionLi = findSessionByName(friend.friendName);
    let sessionListUL = document.querySelector('#session-list');

    if (sessionLi == null) {
        // 如果没有对应的会话
        sessionLi = document.createElement('li');
        sessionLi.innerHTML = '<h3>' + friend.friendName + '</h3>' + '<p></p>';
        sessionListUL.insertBefore(sessionLi, sessionListUL.children[0]);

        sessionLi.onclick = function () {
            clickSession(sessionLi);
        }
        sessionLi.click();

        // 调用后端接口并将会话Id进行存储
        createSession(friend.friendId, sessionLi);
    } else {
        // 有对应的会话
        sessionListUL.removeChild(sessionLi)
        sessionListUL.insertBefore(sessionLi, sessionListUL.children[0]);
        sessionLi.click();
    }
    let tabSession = document.querySelector('.tab .tab-session');
    tabSession.click();
}

function createSession(friendId, sessionLi) {
    $.ajax({
        type: 'post',
        url: 'session/addSession',
        data: {
            toUserId: friendId,
            userId: localStorage.getItem('id'),
        },
        success: function (result) {
            console.log(result);
            console.log("会话创建成功! sessionId = " + result.data);
            sessionLi.setAttribute('message-session-id', result.data);
        },
        error: function () {
            console.log('会话创建失败!');
        }
    });
}

function findSessionByName(friendName) {
    let sessionLis = document.querySelectorAll("#session-list>li");
    for (let sessionLi of sessionLis) {
        let h3 = sessionLi.querySelector('h3')
        if (h3.innerHTML == friendName) {
            return sessionLi;
        }
    }
    return null;
}

function getSessionList() {
    $.ajax({
        type: 'get',
        url: '/session/getSessionList?userId=' + localStorage.getItem('id'),
        success: function (result) {
            let sessionList = document.querySelector('#session-list');
            sessionList.innerHTML = '';

            console.log(result.data);
            for (let session of result.data) {
                let li = document.createElement('li');
                li.setAttribute('message-session-id', session.sessionId);

                li.innerHTML = '<h3>' + session.friends[0].friendName + '</h3>'
                    + '<p>' + session.lastMessage + '</p>';
                sessionList.appendChild(li);

                li.onclick = function () {
                    clickSession(li);
                }
            }

        }
    })
}
getSessionList();

function clickSession(currentLi) {
    // 使被点击的li变亮
    let allLis = document.querySelectorAll('#session-list>li');
    activeSession(allLis, currentLi);

    // 获取对话
    let sessionId = currentLi.getAttribute("message-session-id");
    getHistoryMessage(sessionId);
}

function activeSession(allLis, currentLi) {
    for (let li of allLis) {
        if (li == currentLi) {
            li.className = 'selected';
        } else {
            li.className = ''
        }
    }
}

function getHistoryMessage(sessionId) {
    // 将标题和内容先进行清空
    let titleDiv = document.querySelector('.right .title');
    titleDiv.innerHTML = '';
    let messageShowDiv = document.querySelector('.right .message-show');
    messageShowDiv.innerHTML = '';

    // 将被点击的会话名称填写到对话框上方
    let selectedH3 = document.querySelector('#session-list .selected>h3');
    if (selectedH3) {
        titleDiv.innerHTML = selectedH3.innerHTML;
    }

    // 获取所有的消息
    $.ajax({
        type: 'get',
        url: '/message/getMessagesBySessionId?sessionId=' + sessionId,
        success: function (result) {
            for (let message of result.data) {
                addMessage(messageShowDiv, message);
            }
            scrollBottom(messageShowDiv);
        }
    });
}

function addMessage(messageShowDiv, message) {
    let userId = localStorage.getItem('id');
    let messageDiv = document.createElement('div');

    if (userId == message.fromId) {
        // 自己发送的消息
        messageDiv.className = 'message message-right';
        messageDiv.innerHTML = '<div class="box">'
            + '<h3 class="h3-right">' + message.fromName + '</h3>'
            + '<p class="p-right">' + message.content + '</p>'
            + '</div>';
    } else {
        // 别人发送的消息
        messageDiv.className = 'message message-left';
        messageDiv.innerHTML = '<div class="box">'
            + '<h3>' + message.fromName + '</h3>'
            + '<p class="p-left">' + message.content + '</p>'
            + '</div>';
    }

    messageShowDiv.appendChild(messageDiv);
}

function scrollBottom(elem) {
    let clientHeight = elem.offsetHeight;
    let scrollHeight = elem.scrollHeight;
    elem.scrollTo(0, scrollHeight - clientHeight);
}


// webSocket的初始化设置
let userId = localStorage.getItem('id');
let url = location.host;
// 当访问网址的时候就会建立连接
let webSocket = new WebSocket(`ws://${url}/webSocket?userId=${userId}`);
webSocket.onopen = function () {
    console.log("onopen");
}
webSocket.onmessage = function (element) {
    let response = JSON.parse(element.data);
    console.log(response);
    if (response.type == 'message') {
        // 处理消息响应
        handleMessage(response);
    } else {
        // response 的 type 出错!
        console.log("response.type 不符合要求!");
    }
}

webSocket.onerror = function () {
    console.log('onerror');
}
webSocket.onclose = function () {
    console.log('onclose');
}

function handleMessage(response) {
    // 1.左边消息栏
    let curSessionLi = findSessionLi(response.sessionId);
    if (curSessionLi == null) {
        curSessionLi = document.createElement('li');
        curSessionLi.setAttribute('message-session-id', response.sessionId);
        curSessionLi.innerHTML = '<h3>' + response.fromName + '</h3>'
            + '<p></p>';

        // 点击事件的处理
        curSessionLi.onclick = function () {
            clickSession(curSessionLi);
        }
    }

    let p = curSessionLi.querySelector('p');
    if (response.content.length > 10) {
        response.content = response.content.substring(0, 10) + '...';
    }
    p.innerHTML = response.content;

    // 放到列表最上方
    let sessionListUL = document.querySelector('#session-list');
    sessionListUL.insertBefore(curSessionLi, sessionListUL.children[0]);

    // 2.右边消息框
    if (curSessionLi.className == 'selected') {
        // 把消息列表添加一个新消息. 
        let messageShowDiv = document.querySelector('.right .message-show');
        addMessage(messageShowDiv, response);
        scrollBottom(messageShowDiv);
    }
}

function findSessionLi(sessionId) {
    let sessionLis = document.querySelectorAll('#session-list li');
    for (let li of sessionLis) {
        let temp = li.getAttribute("message-session-id")
        if (temp == sessionId) {
            return li;
        }
    }
    return null;
}

// 给发送按钮进行设置
function initSendButton() {
    let sendButton = document.querySelector('.right .ctrl button');
    let messageInput = document.querySelector('.right .message-input');

    sendButton.onclick = function () {
        if (!messageInput.value) {
            return;
        }

        let selectedLi = document.querySelector('#session-list .selected');
        if (selectedLi == null) {
            // 当前没有 li 标签被选中. 
            return;
        }
        let sessionId = selectedLi.getAttribute('message-session-id');

        let req = JSON.stringify({
            type: 'message',
            sessionId: sessionId,
            content: messageInput.value
        })

        webSocket.send(req);
        messageInput.value = '';
    }
}
initSendButton();